<template>
  <view class="upload-container">
    <view class="image-grid">
      <!-- 已上传图片预览 -->
      <view v-for="(img, index) in imageUrls" :key="index" class="image-item">
        <image :src="img" mode="aspectFill"></image>
        <view class="delete-btn" @click="handleRemove(index)">×</view>
      </view>

      <!-- 上传按钮 -->
      <view
          class="upload-btn"
          @click="handleChooseImage"
          :disabled="imageUrls.length >= maxCount"
      >
        <text>+</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';

// 接收父组件传递的props
const props = defineProps({
  // 已上传的图片列表
  initialImages: {
    type: Array,
    default: () => []
  },
  // 最大上传数量
  maxCount: {
    type: Number,
    default: 9
  },
  // 上传接口URL
  uploadUrl: {
    type: String,
    default: 'http://localhost:10000/oss/upload'
  },
  // 文件类型
  fileType: {
    type: String,
    default: 'article-image'
  },
  // 用户ID
  userId: {
    type: String,
    default: '123'
  }
});

// 定义子组件向父组件传递的事件
const emit = defineEmits(['update:images', 'onUploadError']);

// 图片列表
const imageUrls = ref([...props.initialImages]);

// 选择图片并上传
const handleChooseImage = () => {
  const count = props.maxCount - imageUrls.value.length;
  if (count <= 0) return;

  uni.chooseImage({
    count,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      res.tempFilePaths.forEach(tempPath => {
        handleUpload(tempPath);
      });
    }
  });
};

// 上传图片到服务器
const handleUpload = (tempPath) => {
  uni.showLoading({ title: '上传中...' });

  uni.uploadFile({
    url: props.uploadUrl,
    filePath: tempPath,
    name: 'file',
    formData: {
      fileType: props.fileType,
      userId: props.userId
    },
    success: (res) => {
      if (res.statusCode === 200) {
        const result = JSON.parse(res.data);
        if (result.code === 200) {
          imageUrls.value.push(result.data.url);
          // 通知父组件图片列表已更新
          emit('update:files', imageUrls.value);
        } else {
          uni.showToast({ title: '图片上传失败', icon: 'none' });
          emit('onUploadError', result.message);
        }
      } else {
        uni.showToast({ title: '服务器错误', icon: 'none' });
        emit('onUploadError', '服务器错误');
      }
    },
    fail: (err) => {
      uni.showToast({ title: '上传失败，请重试', icon: 'none' });
      console.error('上传失败：', err);
      emit('onUploadError', err);
    },
    complete: () => {
      uni.hideLoading();
    }
  });
};

// 移除图片
const handleRemove = (index) => {
  imageUrls.value.splice(index, 1);
  // 通知父组件图片列表已更新
  emit('update:images', imageUrls.value);
};

// 暴露给父组件的方法
defineExpose({
  // 获取当前图片列表
  getImages() {
    return imageUrls.value;
  }
});
</script>

<style scoped>
.upload-container {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.image-grid {
  display: flex;
  flex-wrap: wrap;
}

.image-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.image-item image {
  width: 100%;
  height: 100%;
}

.delete-btn {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  border-radius: 50%;
  text-align: center;
  line-height: 40rpx;
  font-size: 32rpx;
  z-index: 10;
  transition: all 0.3s ease;
}

.delete-btn:active {
  background-color: rgba(255, 77, 79, 0.8);
}

.upload-btn {
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #ccc;
  border-radius: 12rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 60rpx;
  color: #ccc;
  transition: all 0.3s ease;
}

.upload-btn:active {
  background-color: #f0f0f0;
}
</style>